//
//  ZCRaiseVC.m
//  zctx
//
//  Created by 郭亚京 on 15/10/9.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCRaiseVC.h"
#import "ZCRaiseCell.h"
#import "ZCMechanismListVC.h"
#import "ZCItemListVC.h"
#import "ZCRaisePayVC.h"

typedef enum {
    RaiseReginTypeProvince = 100,
    RaiseReginTypeCity,
} RaiseReginType;

@interface ZCRaiseVC ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate,UIPickerViewDelegate, UIPickerViewDataSource>{
    UILabel *moneyLable;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIView *viewFooter;

@property (nonatomic, strong) UIButton *buttonSubmit;

@property (nonatomic, strong) UILabel *labelPrice;

@property (nonatomic, strong) UIPickerView *pickView;

@property (nonatomic, strong) UIButton *buttonConfirm;

//data
@property (nonatomic, strong) NSArray *arrProvince;
@property (nonatomic, strong) NSArray *arrCity;
@property (nonatomic, strong) DZRegionProvinceModel *selectProvince;
@property (nonatomic, strong) DZRegionCityModel *selectCity;
@property (nonatomic, strong) NSString *strMechanism;       //检测机构
@property (nonatomic, strong) NSString *strItem;            //检测项目
@property (nonatomic, strong) NSString *strMechanismid;       //检测机构id
@property (nonatomic, strong) NSString *strItemid;            //检测项目id
@property (nonatomic, strong) NSString *pjname;             //项目名称
@property (nonatomic, strong) NSString *pdname;             //产品名称
@property (nonatomic, strong) NSString *citycode;           //城市代码
@property (nonatomic, assign) NSString *emoney;             //套餐价格
@property (nonatomic, assign) NSString *content;             //备注内容

@end

@implementation ZCRaiseVC

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.tableView.shiftHeightAsDodgeViewForMLInputDodger = 44.0f+5.0f;
    [self.tableView registerAsDodgeViewForMLInputDodger];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavigationItems];
    self.selectProvince = self.arrProvince[0];
    
    self.view.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
    self.navigationItem.title = @"发起众筹";
    
    //添加tableview
    [self.view addSubview:self.tableView];
    
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0,0));
    }];
    
    self.arrProvince = [RegionManager getAllProvinces];
    
    /*
    //添加手势
    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer)];
    gestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:gestureRecognizer];
     */
    
}

#pragma mark - request


#pragma mark 提交

- (void)requestSubmit {
    
    NSIndexPath *pjindex = [NSIndexPath indexPathForRow:0 inSection:0];
    NSIndexPath *pdindex = [NSIndexPath indexPathForRow:1 inSection:0];
    NSIndexPath *contentindex = [NSIndexPath indexPathForRow:0 inSection:2];
    ZCRaiseCell *pjcell =(ZCRaiseCell*)[self.tableView cellForRowAtIndexPath:pjindex]; //项目名
    ZCRaiseCell *pdcell =(ZCRaiseCell*)[self.tableView cellForRowAtIndexPath:pdindex];  //品牌名
    ZCRaiseCell *contentcell =(ZCRaiseCell*)[self.tableView cellForRowAtIndexPath:contentindex];  //备注内容
    if (pjcell.textField.text.length<=0) {
        [SVProgressHUD showErrorWithStatus:@"请填写项目名称"];
        return;
    }
    if (pdcell.textField.text.length<=0) {
        [SVProgressHUD showErrorWithStatus:@"请填写品牌名称"];
        return;
    }
    if (!self.selectCity.code) {
        [SVProgressHUD showErrorWithStatus:@"请选择检测城市"];
        return;
    }
    if (!self.strItemid) {
        [SVProgressHUD showErrorWithStatus:@"请选择检测项目"];
        return;
    }
    if (!self.strMechanismid) {
        [SVProgressHUD showErrorWithStatus:@"请选择检测机构"];
        return;
    }
    if (contentcell.textView.text.length<=0) {
        contentcell.textView.text = @"";
    }

    NSLog(@"mid=%@&paaword=%@&pjname=%@&pdname=%@&citycode=%@&brand=%@packageid=%@&institutionid=%@emoney=%@&fromtype=2",UserModel.mid,UserModel.password,pjcell.textField.text,pjcell.textField.text,self.selectCity.code,pdcell.textField.text,self.strMechanismid,self.strItemid,self.emoney);
    
    [NetworkManager requestFoundingPublishWithMid:UserModel.mid
                                         password:UserModel.password
                                           pjname:pjcell.textField.text
                                           pdname:pjcell.textField.text
                                         citycode:self.selectCity.code
                                            brand:pdcell.textField.text
                                        packageid:self.strItemid
                                    institutionid:self.strMechanismid
                                           emoney:self.emoney
                                         fromtype:@"2"
                                          content:contentcell.textView.text success:^(NSDictionary *dictResponse) {
      NSString *errStr = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
      
      if ([errStr isEqualToString:@"0"]) {
          
          ZCRaisePayVC *payvc = [[ZCRaisePayVC alloc]init];
          payvc.priceStr = @"";
          payvc.markStr = @"1";
          payvc.pid = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"content"]];
          [self.navigationController pushViewController:payvc animated:YES];
      }
                                              
                                          } failure:^(NSError *error) {
                                              
                                          }];
}

#pragma mark - button

-(void)setNavigationItems {
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

- (void)backButtonPressed{
    ProgressDismiss;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tapGestureRecognizer {
    [self.view endEditing:YES];
}

- (void)submitButtonClick {
    [self requestSubmit];
}
#pragma mark 地址确认按钮

- (void)confirmButtonClick:(UIButton *)button {
    [self.pickView removeFromSuperview];
    [self.buttonConfirm removeFromSuperview];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    ZCRaiseCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (button.tag == RaiseReginTypeProvince) {
        [cell.buttonCity setTitle:@"城市" forState:UIControlStateNormal];
        self.selectCity = nil;
        DZRegionProvinceModel *model = [self.arrProvince objectAtIndex:[self.pickView selectedRowInComponent:0]];
        self.selectProvince = model;
        [cell.buttonProvince setTitle:model.name forState:UIControlStateNormal];
    } else {
        DZRegionCityModel *modelcity = [self.arrCity objectAtIndex:[self.pickView selectedRowInComponent:0]];
        self.selectCity = modelcity;
        [cell.buttonCity setTitle:self.selectCity.name forState:UIControlStateNormal];
    }
    NSLog(@"self.selectProvive.code = %@ , self.city.code = %@",self.selectProvince.code,self.selectCity.code);
}

#pragma mark - private Methods 显示城市

- (void)showPickerViewWithTag:(RaiseReginType)type {
    [self TextFiledresignFirstResponder];
    if (self.pickView && self.buttonConfirm) {
        [self.pickView removeFromSuperview];
        [self.buttonConfirm removeFromSuperview];
    }
    self.pickView = nil;
    self.pickView.tag = type;
    [self.view addSubview:self.pickView];
    [self.pickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom).with.offset(-50);
        make.height.mas_equalTo(216);
        make.left.mas_equalTo(0);
        make.width.equalTo(self.view.width);
    }];
    self.buttonConfirm = nil;
    self.buttonConfirm.tag = type;
    [self.view addSubview:self.buttonConfirm];
    [self.buttonConfirm mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom);
        make.height.mas_equalTo(50);
        make.left.mas_equalTo(0);
        make.width.equalTo(self.view.width);
    }];
}

#pragma mark - UITableView DataSource & Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    } else if (section == 1) {
        return 2;
    } else if (section == 2) {
        return 1;
    } else {
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIndentity = @"Cell";
    ZCRaiseCell *cell;
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //名称
            cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypeInput];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.labelTitle setText:@"名称："];
            [cell.textField setPlaceholder:@"请填写项目名称"];
            if (self.pushpjName) {
                cell.textField.text = self.pushpjName;
            }
        } else if (indexPath.row == 1) {
            //品牌
            cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypeInput];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.labelTitle setText:@"品牌："];
            [cell.textField setPlaceholder:@"请填写品牌名称"];
        } else {
            //抽样地
            cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypeSelect];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell.labelTitle setText:@"抽样地："];
            cell.blockProvinceButtonClick = ^() {
                [self showPickerViewWithTag:RaiseReginTypeProvince];
            };
            cell.blockCityButtonClick = ^() {
                if (self.selectProvince.code) {
                self.arrCity = [RegionManager getAllCitiesByProvinceCode:self.selectProvince.code];
                    [self showPickerViewWithTag:RaiseReginTypeCity];
                } else {
                    [self showPickerViewWithTag:RaiseReginTypeProvince];
                }
            };
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            //检测机构
            cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypePush];
            [cell.labelTitle setText:@"检测项目："];
            if (self.strItem.length > 1) {
                [cell.labelInfo setText:self.strItem];
            } else {
                [cell.labelInfo setText:@"选择检测项目"];
            }
        } else {
            //检测项目
            cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypePush];
            
            [cell.labelTitle setText:@"检测机构:"];
            if (self.strMechanism.length > 1) {
                [cell.labelInfo setText:self.strMechanism];
            } else {
                [cell.labelInfo setText:@"选择检测机构"];
            }
        }
    } else {
        //备注信息
        cell = [[ZCRaiseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentity cellType:RaiseCellTypeText];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.blockTextViewShouldBeginEdit = ^(){
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(self.view.height).with.offset(-220);
            }];
        };
        cell.blockTextViewDidEndEdit = ^(){
            [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.equalTo(self.view.height);
            }];
        };
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {
        return 60;
    } else {
        return 40;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    [view setBackgroundColor:[UIColor whiteColor]];
   UILabel * titleLable = [[UILabel alloc] init];
    [view addSubview:titleLable];
    [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view.centerY);
        make.height.equalTo(view.height);
        make.left.equalTo(view.left).with.offset(20);
    }];
    titleLable.textColor = [UIColor colorWithHexString:@"#333333"];
    if (section == 0) {
        //基本信息
        [titleLable setText:@"基本信息"];
    } else if (section == 1) {
        //检测信息
        [titleLable setText:@"检测信息"];
    } else if (section == 2) {
        //众筹金额
        [titleLable setText:@"众筹金额(检测金额):"];

        [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(@(160));
        }];
        moneyLable = [[UILabel alloc] init];
        [view addSubview:moneyLable];
        moneyLable.textAlignment = NSTextAlignmentLeft;
        moneyLable.textColor = [UIColor colorWithHexString:@"#ff3d3d"];
        [moneyLable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(view.centerY);
            make.height.equalTo(view.height);
            make.left.equalTo(titleLable.right).with.offset(0);
            make.right.equalTo(view.right).with.offset(-20);
        }];

    } else {
        //温馨提示
        UIImageView *prommptImg = [[UIImageView alloc] init];
        [view addSubview:prommptImg];
        [prommptImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(view.centerY);
            make.height.mas_equalTo(@20);
            make.right.equalTo(titleLable.left).with.offset(0);
            make.width.mas_equalTo(@20);
        }];
        [prommptImg setImage:[UIImage imageNamed:@"raise_prompt"]];
        [titleLable setText:@"温馨提示：发起人提交后必须领投（10元起）"];
        [titleLable setAdjustsFontSizeToFitWidth:YES];
        [titleLable mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@(40));
            make.right.equalTo(view.right).with.offset(-20);
        }];
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    __block  ZCRaiseVC *weekself = self;

    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            //检测项目
            ZCItemListVC *vc = [[ZCItemListVC alloc] init];
            vc.cellselectItemList = ^(NSString *ids,NSString *name,NSString * money){
                ZCRaiseCell *cell = (ZCRaiseCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.labelInfo.text = name;
                weekself.strItem = name;
                weekself.strItemid = ids;
                weekself.emoney = money;
                [moneyLable setText:[NSString stringWithFormat:@"￥%@",money]];
            };
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            //检测机构
            ZCMechanismListVC *vc = [[ZCMechanismListVC alloc] init];
            vc.cellselectMechanismList = ^(NSString *ids,NSString *name){
                ZCRaiseCell *cell = (ZCRaiseCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.labelInfo.text = name;
                weekself.strMechanism = name;
                weekself.strMechanismid = ids;
                NSLog(@"检测机构 = %@",ids);
            };
            [self.navigationController pushViewController:vc animated:YES];
                    }
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}
-(void)TextFiledresignFirstResponder{
    NSIndexPath *pjindex = [NSIndexPath indexPathForRow:0 inSection:0];
    NSIndexPath *pdindex = [NSIndexPath indexPathForRow:1 inSection:0];
    ZCRaiseCell *pjcell =(ZCRaiseCell*)[self.tableView cellForRowAtIndexPath:pjindex]; //项目名
    ZCRaiseCell *pdcell =(ZCRaiseCell*)[self.tableView cellForRowAtIndexPath:pdindex];  //品牌名
    [pjcell.textField resignFirstResponder];
    [pdcell.textField resignFirstResponder];
}

#pragma mark - UIGestureRecognizerDelegate Methods

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UITableViewCell class]]) {
        return NO;
    } else {
        return YES;
    }
}

#pragma mark - UIPickViewDelegate & Database Methods

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView.tag == RaiseReginTypeProvince) {
        return self.arrProvince.count;
    } else if (pickerView.tag == RaiseReginTypeCity) {
        return self.arrCity.count;
    }
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (pickerView.tag == RaiseReginTypeProvince) {
        DZRegionProvinceModel *model = self.arrProvince[row];
        return model.name;
    } else if (pickerView.tag == RaiseReginTypeCity) {
        DZRegionCityModel *model = self.arrCity[row];
        return model.name;
    }
    return @"";
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

#pragma mark - instance 

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = self.viewFooter;
    }
    return _tableView;
}

- (UIView *)viewFooter {
    if (!_viewFooter) {
        _viewFooter = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
        
        //提交
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(20, 10, SCREEN_WIDTH-40, 40)];
        [button setBackgroundImage:[UIImage imageNamed:@"raise_confirm_bg"] forState:UIControlStateNormal];
        [button setTitle:@"提 交" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(submitButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.viewFooter addSubview:button];
    }
    return _viewFooter;
}

- (UIPickerView *)pickView {
    if (!_pickView) {
        _pickView = [[UIPickerView alloc] init];
        [_pickView setBackgroundColor:[UIColor whiteColor]];
        _pickView.delegate = self;
    }
    return _pickView;
}

- (UIButton *)buttonConfirm {
    if (!_buttonConfirm) {
        _buttonConfirm = [UIButton buttonWithType:UIButtonTypeCustom];
        [_buttonConfirm setTitle:@"确定" forState:UIControlStateNormal];
        [_buttonConfirm setTitleColor:[UIColor colorWithHexString:@"666666"] forState:UIControlStateNormal];
        [_buttonConfirm setBackgroundColor:[UIColor whiteColor]];
        [_buttonConfirm addTarget:self action:@selector(confirmButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buttonConfirm;
}

@end
